import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;


import javax.swing.*;
import java.io.*;
public class Window extends JPanel implements Runnable, TBObserver
{
	//screen
	
	public static Image[] tileset_ground = new Image[100]; //import images
	public static Image[] tileset_air = new Image[100]; //import air images
	public Thread gameloop = new Thread(this);
	public static boolean isFirst = true; //
	public static int myWidth, myHeight;
	public static Room room;
	private int Xcoordinate = 0;
	private int Ycoordinate = 0;
	public static Save save;
	public int currentImage; //for TBObs
	public boolean buildable, passable; //for TBObs
	
	
	
	
	
	
	public Window() //create the window on frame
	{
		gameloop.start();
		
		addMouseListener(new MouseAdapter() 
		{

			public void mousePressed(MouseEvent e) 
			{
				Xcoordinate = e.getX();
				Ycoordinate = e.getY();
				//System.out.println("The (X,Y) coordinate of window is ("
						//+ Xcoordinate + "," + Ycoordinate + ")");
				
				
				Xcoordinate = (int) Math.floor((Xcoordinate - 32)/52);
				Ycoordinate = (int) Math.floor((Ycoordinate)/52);
				
				//System.out.println("The BLock is: " + Xcoordinate + " " + Ycoordinate);
				Window.room.blockArray[Ycoordinate][Xcoordinate].groundID = currentImage;
			}
		
		});
		
	}
	
	
	public void define()
	{
		room = new Room();
		save = new Save();
		
		for(int i = 0; i<tileset_ground.length; i++)
		{
			tileset_ground[i] = new ImageIcon("res/tileset_ground.png").getImage(); //get source of image from tilesetground
			tileset_ground[i] = createImage(new FilteredImageSource(tileset_ground[i].getSource(), new CropImageFilter(0, 26*i, 26, 26))); //then crop the image according to i
		}
		
		for(int i = 0; i<tileset_air.length; i++)
		{
			tileset_air[i] = new ImageIcon("res/tileset_air.png").getImage(); //get source of image from tilesetair
			tileset_air[i] = createImage(new FilteredImageSource(tileset_air[i].getSource(), new CropImageFilter(0, 26*i, 26, 26))); //then crop the image according to i
		}
		
		save.loadSave(new File("save/mission1.save"));
	}
	
	public void paintComponent(Graphics g) //
	{
		if(isFirst)
		{
			myWidth = getWidth();
			myHeight = getHeight();
			define();
			isFirst = false;
		}
		
		
		g.clearRect(0, 0, getWidth(), getHeight());//clear a blank space on the window
		
		room.draw(g); //drawing the room
	}
	
	
	
	public void run()
	{
		while(true)
		{
			if(!isFirst)
			{
				
				room.physics();
			}
			
			repaint();
			try
			{
			Thread.sleep(1);
			}
			catch(Exception e)
			{
				
			}
		}
	}


	


	public void update(int ImageInt, Boolean b, Boolean p) {
		currentImage = ImageInt;
		buildable = b;
		passable = p;
		
	}


	
	
	
}
